package com.lession.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lession.Dto.AiReqDto;
import com.lession.controller.AiController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Service
public class AiService {
	private final static Logger logger = LoggerFactory.getLogger(AiService.class);
	
	@Value("${API_KEY}")
	private String API_KEY;
	
	public JSONObject aiOne(AiReqDto dto) {
		JSONObject result = new JSONObject();
		try {
			String role = dto.getRole();
			String content = dto.getContent();
			if (StringUtils.isBlank(role)) {
				role = "user";
			}
			if (StringUtils.isBlank(content)) {
				result.put("msg", "输入内容不能为空");
				return result;
			}
			JSONObject reqJson = new JSONObject();// 创建请求体
			reqJson.put("model", "qwen-plus");
			JSONArray msgArr = new JSONArray();
			JSONObject msgObj = new JSONObject();
			msgObj.put("role", role);
			msgObj.put("content", content);
			msgArr.add(msgObj);
			reqJson.put("messages", msgArr);

			// 创建 URL 对象
			URL url = new URL("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions");
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

			// 设置请求方法为 POST
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
			httpURLConnection.setRequestProperty("Accept", "application/json");
			// 若没有配置环境变量，请用百炼API Key将下行替换为：String apiKey = "sk-xxx";
			String auth = "Bearer " + API_KEY;
			httpURLConnection.setRequestProperty("Authorization", auth);
			// 启用输入输出流
			httpURLConnection.setDoOutput(true);
			// 写入请求体
			try (OutputStream os = httpURLConnection.getOutputStream()) {
				byte[] input = reqJson.toString().getBytes(StandardCharsets.UTF_8);
				os.write(input, 0, input.length);
			}
			// 获取响应码
			int responseCode = httpURLConnection.getResponseCode();
			System.out.println("Response Code: " + responseCode);
			// 读取响应体
			try (BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8))) {
				StringBuilder response = new StringBuilder();
				String responseLine;
				while ((responseLine = br.readLine()) != null) {
					response.append(responseLine.trim());
				}
				logger.info("AI-RESPONSE:{}",response);
				if(StringUtils.isNotBlank(response)){
					JSONObject jsonObject = JSONObject.parseObject(response.toString());
					JSONArray choices = jsonObject.getJSONArray("choices");
					if(!choices.isEmpty()){
						result.put("msg", choices.getJSONObject(0).getJSONObject("message").getString("content"));
					}else {
						result.put("msg", "ai返回为空");
					}
				}else{
					result.put("msg", "ai返回为空");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("调用ai异常!",e);
		}
		return result;
	}
}
